package model

import (
	"example/initDB"
	"fmt"
)

type HeroModel struct {
	Id         string `json:"id"`
	Name       string `json:"name"`
	Forces     string `json:"forces"`
	SkillOne   string `json:"skillOne"`
	SkillTwo   string `json:"skillTwo"`
	SkillThree string `json:"skillThree"`
	SkillFour  string `json:"skillFour"`
}

// Add 新增
func (h *HeroModel) Add() int64 {
	res, _ := initDB.Db.Exec("insert into hello.hero (name,forces,skillOne,skillTwo,skillThree,skillFour) values (?,?,?,?,?,?);",
		h.Name, h.Forces, h.SkillOne, h.SkillTwo, h.SkillThree, h.SkillFour)
	id, _ := res.LastInsertId()
	return id
}

// Edit 编辑
func (h *HeroModel) Edit() bool {
	_, e := initDB.Db.Exec("update hello.hero set name = ?,forces = ?,skillOne=?,skillTwo=?,skillThree=?,skillFour=? where id=?;",
		h.Name, h.Forces, h.SkillOne, h.SkillTwo, h.SkillThree, h.SkillFour, h.Id)
	if e != nil {
		return false
	}
	return true
}

// Search 查询
func (h *HeroModel) Search(name string) ([]HeroModel, error) {
	sqlStr := "select * from hello.hero where name like ?"
	res, e := initDB.Db.Query(sqlStr, "%"+name+"%")
	//defer res.Close()
	arr := make([]HeroModel, 0)
	for res.Next() {
		var her HeroModel
		err := res.Scan(&her.Id, &her.Name, &her.Forces, &her.SkillOne, &her.SkillTwo, &her.SkillThree, &her.SkillFour)
		if err != nil {
			return nil, err
		}
		arr = append(arr, her)
	}
	return arr, e
}

// Del 删除
func (h *HeroModel) Del(id string) bool {
	fmt.Println("id= " + id)
	sqlStr := "delete from hello.hero where id=?"
	_, e := initDB.Db.Exec(sqlStr, id)
	if e != nil {
		return false
	}
	return true
}
